import app from '@/app'
import { get, create, del, status } from '@/api/store/voucher'
import printer from '@/model/printer'
import config from '@/plugin/config/model'

import base from '@/app/model'

// 继承总模型
const model = new base;

model.get = () => {
  return new Promise((resolve, jeject) => {
    app.ui.loading()
    get(model.getData()).then(res => {
      model.setList(res.data)
      // 分页
      model.setData(Object.assign(model.getData(), {
        page: res.current_page,
        page_size: res.per_page,
        page_total: res.total
      }))
      resolve(res)
    }).catch(res => {
      jeject(res)
    }).finally(() => {
      app.ui.loadingClose()
    })
  })
}

model.create = async(data) => {
  // 生成 code
  data.code = await config.code('voucher')
  return new Promise((resolve, jeject) => {
    create(data).then(res => {
      model.get()
      app.ui.message('success', res.message)
      // 创建及打印
      model.print(data)
      resolve(res)
    }).catch(res => {
      app.ui.message('error', 'error.' + res.message)
      jeject(res)
    })
  })
}

model.del = (...arge) => {
  return new Promise((resolve, jeject) => {
    del(...arge).then(res => {
      model.get()
      app.ui.message('success', res.message)
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

// 核销
model.status = (data) => {
  return new Promise((resolve, jeject) => {
    status(data).then(res => {
      model.get()
      app.ui.message('success', res.message)
      // 找零
      model.change(data)
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

// 找零
model.change = (data) => {
  // 代金劵减核销金额
  const change = Number(data.money) - Number(data.status_money)

  // 如果大于 0 说明有找回代金劵,原样创建
  if(change > 0) {
    data.money = change
    model.create(data)
  }
}

// 打印
model.print = (data) => {
  printer.printTemplate('voucher', data)
}

model.page = (page) => {
  model.getData().page = page
  model.get()
}

export default model